<template>
  <div class="topTitle">
    <div>{{ props.typeName || props.title }}</div>
    <NButton style="width: 78px; margin-right: 10rem" type="primary" @click="openModal(true)">
      同意
    </NButton>
    <NButton ghost style="width: 78px; margin-right: 10rem" type="error" @click="openModal(false)">
      拒绝
    </NButton>
    <NButton style="width: 78px;" color="#60abb1" type="info" @click="openEnd" v-if="props.assigneeFlag == 1">
      加签
    </NButton>
  </div>

  <NModal :auto-focus="false" v-model:show="formValue.modalVisible" :mask-closable="false">
    <VDialogContent
      @close="; (formValue.modalVisible = false), (formValue.opinions = null), (formValue.identifyingName = null)"
      @submit="submit" :title="formValue.title">
      <NForm ref="formRef" require-mark-placement="left" label-placement="left" label-align="right"
        :label-width="formValue.title == '加签' ? 100 : 85" :rules="rules" :model="formValue">
        <div class="main" v-if="formValue.title != '加签'">
          <NFormItem label="采购方式:" path="otherParam" v-if="props.otherParamFlag">
            <NSelect v-model:value="formValue.otherParam" placeholder="请选择采购方式" clearable style="width: 250rem; "
              :options="otherParamList" />
          </NFormItem>
          <!-- 信访详情 - 当前步骤被加签且不是最后一个审批人同意（需要上传附件） -->
          <NFormItem label="附件:" path="fileId" v-if="props.assigneeIdentifying && formValue.resultFlag">
            <VUpload :file-list="fileList" type-accept=".doc,.docx,.pdf" @getList="handleUploadList" />
          </NFormItem>
          <NFormItem label="备注:" path="opinions">
            <NInput ref="vialogBlur" v-model:value="formValue.opinions" placeholder="请输入备注" clearable type="textarea"
              style="width: 250rem; height: 100rem; " :allow-input="noSideSpace" />
          </NFormItem>
        </div>
        <div class="endMain" v-else>
          <NFormItem label="选择加签用户:">
            <div style="width: 100%; display: flex; flex-direction: column">
              <NButton style="width: 115px; margin-bottom: 10rem" type="primary" ghost
                @click="formValue.scopeVisible = true">
                选择加签用户
              </NButton>
              <div class="scope" v-if="formValue.identifyingName">{{ formValue.identifyingName }}</div>
            </div>
          </NFormItem>
          <NFormItem label="备注:" path="opinions">
            <NInput v-model:value="formValue.opinions" placeholder="请输入备注" clearable type="textarea"
              style="width: 250rem; height: 100rem" :allow-input="noSideSpace" />
          </NFormItem>
        </div>
      </NForm>
    </VDialogContent>
  </NModal>
  <!-- 范围选择 -->
  <NModal :auto-focus="false" v-model:show="formValue.scopeVisible" @close="formValue.scopeVisible = false">
    <VScope @close="formValue.scopeVisible = false" @scopeSubmit="getScopeList" :defaultList="formValue.scopeOrPeopleList"
      :flat="true" :radioFlat="true" />
  </NModal>
</template>

<script setup lang="ts">
import { reactive, nextTick, ref } from 'vue'
import { useMessage, NButton, NModal, NInput, NForm, NFormItem, type FormInst, NSelect } from 'naive-ui'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import VUpload from '@/views/OA/Common/UploadForDisOrEnd.vue'
import VScope from '@/views/OA/Common/Scope.vue'
import { userCenterStore } from '@/stores/notice'
import { useTagStore } from '@/stores/layout'
import router from '@/router'

const useStore = userCenterStore()
const tags = useTagStore().tags

const props = defineProps({
  id: { type: [String, Number] },
  assigneeFlag: { type: [String, Number] },
  typeName: { type: [String] },
  title: { type: [String], default: () => '申请单' },
  otherParamFlag: { type: Boolean, default: () => false },
  assigneeIdentifying: { type: Boolean, default: () => false }
})
const otherParamList = [
  { label: '公开招标', value: '公开招标' },
  { label: '邀请招标', value: '邀请招标' },
  { label: '竞争性谈判', value: '竞争性谈判' },
  { label: '竞争性磋商', value: '竞争性磋商' },
  { label: '单一来源采购', value: '单一来源采购' },
  { label: '询价', value: '询价' },
  { label: '政采云', value: '政采云' },
  { label: '自行采购', value: '自行采购' }
]
const message = useMessage()
const formValue = reactive<Record<string, any>>({
  title: null,
  resultFlag: false,
  modalVisible: false,
  opinions: null,
  scopeVisible: false,
  scopeOrPeopleList: [],
  identifyingId: null,
  identifyingName: null,
  otherParam: null,
  fileId: null
})
const rules: any = {
  opinions: {
    required: false,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入备注')
      if (value?.length > 500) return new Error('备注字数不得超过500')
      return true
    }
  },
  otherParam: {
    required: true,
    message: '请选择采购方式',
    trigger: ['change', 'select']
  },
  fileId: {
    required: true,
    validator: (_: any, value: any) => {
      if (!value) return new Error('请上传附件')
    }
  }
}
// 限制前后空格
const noSideSpace = (value: string) => !value.startsWith(' ') && !value.endsWith(' ')
// 发布范围选择
const getScopeList = (v: any) => {
  formValue.scopeOrPeopleList = v
  formValue.identifyingName = formValue.scopeOrPeopleList.map((it: any) => it.typeName).join(',')
  formValue.identifyingId = formValue.scopeOrPeopleList.map((it: any) => it.identifyingId).join(',')
  formValue.scopeVisible = false
}
// 打开modal
const vialogBlur: any = ref(null)
const openModal = (flat = true) => {
  formValue.title = '审批'
  formValue.resultFlag = flat
  flat ? (formValue.opinions = '同意') : (formValue.opinions = '拒绝')
  formValue.modalVisible = true
  nextTick(() => vialogBlur.value?.blur())
}
// 点击加签
const openEnd = () => {
  formValue.title = '加签'
  formValue.resultFlag = false
  formValue.opinions = '同意并加签'
  formValue.modalVisible = true
}
// 提交
const formRef = ref<FormInst | null>(null)
const submit = () => {
  formRef.value?.validate(async (err) => {
    if (err) return
    if (formValue.title == '加签') {
      if (!formValue.scopeOrPeopleList?.length) return message.error('选择加签用户')
      dispatchEndorse()
    } else dispatchDispose()
  })
}
// 审批
const dispatchDispose = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'dispose',
    api: 'approve',
    override: {
      data: {
        assigneeFlag: false,
        resultFlag: formValue.resultFlag,
        fromId: props.id,
        opinions: formValue.opinions,
        otherParam: formValue.otherParam,
        fileIds: formValue.fileId
      }
    }
  })
  formValue.modalVisible = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success('审批成功')
  useStore.getTopCount()
  goBack()
}
// 加签
const dispatchEndorse = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'dispose',
    api: 'approve',
    override: {
      data: {
        assigneeFlag: true,
        fromId: props.id,
        identifyingName: formValue.identifyingName,
        identifyingId: formValue.identifyingId,
        opinions: formValue.opinions
      }
    }
  })
  formValue.modalVisible = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success('加签成功')
  goBack()
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}

// 附件
const fileList = ref()
const handleUploadList = (v: any) => (formValue.fileId = v)
</script>

<style scoped lang="scss">
.topTitle {
  font-size: 22px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  color: #5fb17f;
  margin-bottom: 10rem;
}

.main {
  display: flex;
  flex-direction: column;
}

.endMain {
  display: flex;
  flex-direction: column;
}

.scope {
  display: flex;
  align-items: center;
  width: 100%;
  min-height: 50rem;
  background-color: #e1e1e1;
  padding: 0 10rem;
}
</style>
